# -*- coding: utf-8 -*-
import base64
import binascii
import json
from datetime import datetime

import requests
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Hash import SHA
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from django.conf import settings

from common.bankcard.model import BANK_DCT
from common.mch import handler as mch_handler
from common.timer import TIMER_EVENT_TYPE
from common.timer.handler import submit_notify_event
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import local_now
from common.withdraw import db as withdraw_db
from common.withdraw.model import WITHDRAW_ORDER_STATUS
from common.mch.db import get_account

_LOGGER = track_logging.getLogger('withdraw')

APP_CONF = {
    '5433': {
        'gateway': 'https://api.onepay.solutions/v2/distribute/withdraw.html',
        'query_gateway': 'https://api.onepay.solutions/v2/distribute/queryWithdraw.html',
        'pub_key': """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmwwFxxkClvsBzZUtE0CN4S7P0QWZxnpxn2De0zlqbjY6Put/8738SXYkGsuBIb5QZU3tDb/0hmON3zQ84BLexksP2iNqY1q1VSeY2NkV/QxrCUefUedTFsDU+ZcIB5JJ02m4fqpYtzYowtf5JrgjYHcyrO1IaX3NVITm9EPOMHQIDAQAB
-----END PUBLIC KEY-----""",
        'pri_key': """-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAKYYfBLYpXy31d8GFTasdxMOpCyeDOdBq7Nnqjv5nCopXAZE8bS61gCjgEnZuCB5lL+1NXUvN6KTnV3Qobf/n5nWJWGIg8MV3rlrs+Ne73ZltUKUa6wFiBRaXQm/J8K6lw1A49r3vaWgPm3gsmXKd6Cs4KN2SQyxIqYBOJ8QOPjjAgMBAAECgYBYBDeToRyo5549LjMFowUCo0qanjKGRcWgL3oFiDOaIAq1A8n2FOAcvIfaGra49tS9dmBatefMjl7g/RMFtz8yXoef4XW2jDqXDQ4xyfcxMLkmg+TKBkWQnijNzpH0OMt6oqfwLqaBoJiPUgCXG9EMguu+bdd1QYeHWqjkQHH9KQJBAPrc+Qim7I7SHM9fmq7NkqpeYX7PWi59TGL94zu9JjaDHQG/uknQJUbeehf1HESlwi3bdlIpDe0KdUzi/VcvrQ8CQQCpfyjeh1ZoBa48+pciAz7k393qFn5ESekHZNdkzhE8ZMMj6hn7W9sgbf7Ou6R/QDGhb2rMWP9INoY1+QpsUh7tAkEAlH4Cp11vf2beCN5ViI1E+LXfThndDtG6SopwXGctXG0l2WgtFA4yUo3UhaPgNL5Nf6l9k0qb5KkhH/7o6RfefwJAeSy8hiKRRnrRLy0jwSA65ZuaZhFAogeI/k08pAeiUN/klpd1jbsEtHGO2jNSDdtR4AzseD0j/Hdmic2KgxhOnQJAV29jpedsVprVXFY9TjYErqgCoRoFSulyjpdQEAY+UHd0D/QIRCcptH2PeoVXPE/CS9EnuEz9VUYS47Pv1EEJZw==
-----END PRIVATE KEY-----""",
    },
    '3765': {
        'gateway': 'https://api.onepay.solutions/v2/distribute/withdraw.html',
        'query_gateway': 'https://api.onepay.solutions/v2/distribute/queryWithdraw.html',
        'pub_key': """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmwwFxxkClvsBzZUtE0CN4S7P0QWZxnpxn2De0zlqbjY6Put/8738SXYkGsuBIb5QZU3tDb/0hmON3zQ84BLexksP2iNqY1q1VSeY2NkV/QxrCUefUedTFsDU+ZcIB5JJ02m4fqpYtzYowtf5JrgjYHcyrO1IaX3NVITm9EPOMHQIDAQAB
-----END PUBLIC KEY-----""",
        'pri_key': """-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAJMtJBuKcQq6l6dJ1z31VghRJF4SAy2b3YEulOlmrE49yWxzk8S4tngP1jIU6N7h67bI6oaDjKWSjv44JWgFlp/0pV0Na1GY+dLtimMkz9Rqh8dPJgGLvFQNeeiNpObCk6u9rSkbPMbfyaBqotVfb8LurkFpLK7sqUYZmpBmBvo5AgMBAAECgYBcurhhUdzfcalTkca4FvfZzaYoTxkJh4cMeZkBZdtygKOEXV3hOLBe/Ttr2pjOtXGafQSnNANN3wWRTzbiT4MS2IE5NbEpKn9RSyoKUVe7keg9IEWMVNe+W5xefQhOprl88hY0hiR/set7sgQEbaba6oZ/HEfoHcEcuBgOekuccQJBAMly+5B0rWu9puTIGulyiokDtYydt+HqCtw2punVstwt26+JXGTNcGefooE9fb4yLYicemeuKGTB6VjwRQutIw8CQQC7B9CrMujySOuEQxQ1GjOgRVvU0UR3LnGkwm/7ApaUyIof7Q1WLwXIhJKShtr60aekZ8UnS0N2z0Rke4hE/G43AkEAlzkOqYE9Eg0bdNDWivpmDrbPGZDoEdosbuVD5XN7QhfWu24lArLJt7A5QEWV2Co4zj2REbXGMuTyM8aiPkKpdwJAKbeSib0vTGuLbNLxfO69OTB/TTboSJUpcBCWnax0HfelJ33ejayrY5B+iQRfb7a35+nlheA5yhRtMuSC/rA3fQJABFsLEwfZpO0m9MKukOJDCEppncOFSJutKAgRRoihEj/TNJ2dgUX6UHIDypo9zyNO3Cc/8u/huYEoalFhfYBDhg==
-----END PRIVATE KEY-----""",
    },
    '3885': {
        'gateway': 'https://api.onepay.solutions/v2/distribute/withdraw.html',
        'query_gateway': 'https://api.onepay.solutions/v2/distribute/queryWithdraw.html',
        'pub_key': """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmwwFxxkClvsBzZUtE0CN4S7P0QWZxnpxn2De0zlqbjY6Put/8738SXYkGsuBIb5QZU3tDb/0hmON3zQ84BLexksP2iNqY1q1VSeY2NkV/QxrCUefUedTFsDU+ZcIB5JJ02m4fqpYtzYowtf5JrgjYHcyrO1IaX3NVITm9EPOMHQIDAQAB
-----END PUBLIC KEY-----""",
        'pri_key': """-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAK1zHTJ9234MadfLkRsJpVlQDWurvyYc9A05XPvau2E/Bi+fEn3uwA8dXv7BJSxYZgrPgXUlywow7G0tCmgTj3qmc1GAtQ13LQVi3Th3OBL0vgv0tLqNrA7BIIcGVZfDOLJbXB6MZinBmGHOhwaw0VScLpYnmT26sfIbvnJYqujTAgMBAAECgYAAzqVXI9DOsF4Zu//L4WqclMvLMXxtP/s+yIKPRYBTvohX1mSuo1rPdzKG+v0iTLME39xZYDimrn2bMHd47oZfaMbzq9wL/qKR9FJSBg+jo5o7a/xm2I8oaJib36ygu5m+KaMnulMB4p5fLKVWQhRgjkE5aNrVr5Ag0ifVlTdxKQJBAO5y7a9uJ3w2C1bvlrHUqLSsdc707HKW1kR6cb3BRH6vBYesxhNYnohosh2islHTkruSibasL5pBY8jUtAL18/8CQQC6N2kDCOjD7u2MHgYsEkAUh+nmG29K7B6segr5QpEv/orvHdUh+73l4B9PGUnzBZ4YMOTs8aMyONZE7v/CzPstAkAiUxT3/eldLgJv30lYC/7FE1ZaFlO7Iw9xCBc7c4jCm7s2Dp7sxgL8K+YH8hWtRcGHks6UJzErCWKt1ECddH5NAkEAmAJHbLzHFbpim3Ce5Tb4rEnOe5KFpQleeLkfYB4g2qbUzyDxLM6NU6tCo5UnMoSxa1nuZiVSbNrMvnTCv0gI+QJARA/tve+MLm+Y9UnB7S8PY2mlJsEHSuzGTxXWjUoFwNPPzV5dd4ttssOVaadiJ9NVSJD7eL5YqxItehZUueJBhg==
-----END PRIVATE KEY-----""",
    },
    '3931': {
        'gateway': 'https://api.onepay.solutions/v2/distribute/withdraw.html',
        'query_gateway': 'https://api.onepay.solutions/v2/distribute/queryWithdraw.html',
        'pub_key': """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmwwFxxkClvsBzZUtE0CN4S7P0QWZxnpxn2De0zlqbjY6Put/8738SXYkGsuBIb5QZU3tDb/0hmON3zQ84BLexksP2iNqY1q1VSeY2NkV/QxrCUefUedTFsDU+ZcIB5JJ02m4fqpYtzYowtf5JrgjYHcyrO1IaX3NVITm9EPOMHQIDAQAB
-----END PUBLIC KEY-----""",
        'pri_key': """-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJ8Nyu5zVADnp4RL4Pj9v1BjxoBkOtCXQodu5Vj0eFeL6L2IyW7S+2UGlCIXxaVv/+EMiD0IPVzKiFuPWVlHvOkDuS7ISrLAG/EkLtEzxXWun07MrYOgOQ5Hc7kb3HC5IuINiaLfoqDlLHsIP1TMbRHpLbjkTFdmJ5m2ITqEFEbfAgMBAAECgYBnDCyZ6KZYH73sfKy5JM06bCpDLKzeT+GOlU6KH3mIXuDfSywWXSL7BRQcMoKe+L0zNUdfI2N+JsnJaEpfCZdd6fY4RfxxYDB4qPMLOVw1sq8K09ZhmQ02KOJ9rK6lXyg4nhwVdvcFaGZuy5jvuZpc0p/GfBdzbHrGiTP/8jMagQJBANq0Tfyf75u3JAXWQlpBXaltxZ+4KS4Nw/xo+/siLM7OGmU+/v4wxjzNfK5v3RnTsWON5MBMaQjB59lYCJuSFC8CQQC6LWet/8D3xDny/FWR3kvgy/iHmzIsn5YUY6qJ7FfyECUSZr0i/ccUDbmIhrw/F1MVPIJJ+Nf8HvElJStoVVxRAkEAvP2cetbWnvAm7+hUFFxyDKxwX3IsG8EHgIJUZZMFt3xBMQa8IXqShA5qVO8T2HKn0sjWSRp+lXPC332EirM0PwJASt6FijiGblzv/OIyuyVNGEqOWGI17DIFFY/6/doYh9SsQ9kjCFZL36mhSeD9BNYpaCncL0kt+kqrKQfoi91/8QJBAJl7tdEEpi9wY+9Pi6Xe6L9ZLh3SZ1xNFGxtTpQEn8yzlKQc0r8xFYQeSQWFCneORV26tc1OQRPXtW3L2ETXzUE=
-----END PRIVATE KEY-----""",
    },
    '3933': {
        'gateway': 'https://api.onepay.solutions/v2/distribute/withdraw.html',
        'query_gateway': 'https://api.onepay.solutions/v2/distribute/queryWithdraw.html',
        'pub_key': """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmwwFxxkClvsBzZUtE0CN4S7P0QWZxnpxn2De0zlqbjY6Put/8738SXYkGsuBIb5QZU3tDb/0hmON3zQ84BLexksP2iNqY1q1VSeY2NkV/QxrCUefUedTFsDU+ZcIB5JJ02m4fqpYtzYowtf5JrgjYHcyrO1IaX3NVITm9EPOMHQIDAQAB
-----END PUBLIC KEY-----""",
        'pri_key': """-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBANVQEJxdHTNEzpMHRS7ZInxUnWGq6KvZjnWMJYnDzTYRg2QuKILakgXOhA5ueAfhyq+6HsGS63GPh7EUyRCvUY8g8mMK4MzlVcq1CTtjKHOYvFVahipRWgyVeNdhaTfZe9bmhPvLZpJkAQuUQ4KAupxTCvSi6NCtHTrJERxU/zslAgMBAAECgYBC5MDQyEKH+WPup7ECaAVwh/hy0G32tlr+cdyzvztzYTqbB/6cSn7QY1r2S55Imn49bViHy9MZ4bDjz2jeWpxwezH0Qwf5FIGm0xhHtvPfgjt8EH5vFBDVjrHnrgZv1pN1Hr41sT1yCRPZkSAVMKo2fqLDM7oIvbgxyuYd8owQAQJBAPpqGXDbt7xvRTblXckxg3lt4IT9aPKfJS/zn6g72Pom9JW+kxYbThLmgkI8Wymcz+0v0L8P70pQvOPxJXmHeKUCQQDaEhwZa0WiI905l5+g/rrVVEHdE5Kaa9yKZb+leFVxYH88gTJn7UGlCPcSh9KHdDSFbea5VMn4qQXHVKsdgrCBAkEA7RNR7rU1qGK35pcUSYxk6quJ6p53o2vkKxe9SesPKxWCbdq1KjLDocU2ATtfG3BosieYu6p8Y6E4k50UW5BUOQJACnOVvy4h/zxizPDUaL3srG7GXVcjzpzezA9GWSLkTXPHhVnX1Z1MaSF93fh+gZlzLvXuefFzYKSRL1WCgf6SgQJBAJvQnxL/YcLQyXwnoR7dBlQ8qb8bDkQjCRLBvGi6VgnPiTcz1v6NEhW34LxapZn52uaw/ld/mT2hUBAP3cou3CU=
-----END PRIVATE KEY-----""",
    },
    '4069': {
        'gateway': 'https://api.onepay.solutions/v2/distribute/withdraw.html',
        'query_gateway': 'https://api.onepay.solutions/v2/distribute/queryWithdraw.html',
        'pub_key': """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmwwFxxkClvsBzZUtE0CN4S7P0QWZxnpxn2De0zlqbjY6Put/8738SXYkGsuBIb5QZU3tDb/0hmON3zQ84BLexksP2iNqY1q1VSeY2NkV/QxrCUefUedTFsDU+ZcIB5JJ02m4fqpYtzYowtf5JrgjYHcyrO1IaX3NVITm9EPOMHQIDAQAB
-----END PUBLIC KEY-----""",
        'pri_key': """-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBALWwTHGsHTN/e16itSUQox/DYI6Ofeiub/FoKNuWf6/yWJpu/LwvEa6TtLlPiZcWsurRhr60CUVdJPygpoFEWxG7xp3PBHoEtkxJJS/rrMoYKwkYyVonWh/PjUdVTFywAZuM+RCjOfMXJGHDGdJkmnb01LAOEt08w0tv1A5Ty8lTAgMBAAECgYBKS4hG51mdiGC7Zw9p067Qu0UNpkjoUARok+45NQaLvS7sH7xre1fgqne5W0PpK5gIG5vc+aPc4GTShSLxMzGFkq/nVk6xUOgJlpxUqsYlslJDM41aUkvBh6ncuoGJpNGBGW5KcbH27skoDPZ8MkRskkYRAr6eGhgAdNbG6lkHOQJBAO1v/xElp1Pp2ZMClTVD2x98nilJwJRYNKez798Dk9Qre6Ag6boHFqQixnfM6QYrIBBNuWJwNLVak2wgKLJngT0CQQDD5I/WbgoDdqHlJO66A1Pch7v403add4M/gcxEhbWqBxx3vrIN3f/agf68Sv/i//oQPktTzYWz86pk3CT49f3PAkBz+IHy1BtYZx34KgjKzWvXgzyVGgrP6g095CtDGDI6LUriuXCvhgrO/JVHqnQeqS2uCOiFZhy4f5cF9ucpzFhZAkAyd4vm/mpuAf4rfpxSJ9FPG1j9/dytLMEPd20cqiXnK/XVk7djgzILJTpvYBMUdEYEMUhOysALYFchrOWJjjZZAkEApxkm6n1almwuytu5tXxDJId5D9hIFHumydwZksqkC3yZXwHk5lAdaBGHAQfjcN+vg0TJ3IuebdSo4GUAVm2XnQ==
-----END PRIVATE KEY-----""",
    },
    '4071': {
        'gateway': 'https://api.onepay.solutions/v2/distribute/withdraw.html',
        'query_gateway': 'https://api.onepay.solutions/v2/distribute/queryWithdraw.html',
        'pub_key': """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDmwwFxxkClvsBzZUtE0CN4S7P0QWZxnpxn2De0zlqbjY6Put/8738SXYkGsuBIb5QZU3tDb/0hmON3zQ84BLexksP2iNqY1q1VSeY2NkV/QxrCUefUedTFsDU+ZcIB5JJ02m4fqpYtzYowtf5JrgjYHcyrO1IaX3NVITm9EPOMHQIDAQAB
-----END PUBLIC KEY-----""",
        'pri_key': """-----BEGIN PRIVATE KEY-----
MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKRClyH35cUcr70LoWxWnz5mKAFAyv3tX6Vf24n5Bp1R+7WpYOwYenhFzF/UF+6aoftEMhPF7teX7WdVFJZCpoKoZWFuNM6/HPQyExR6+NwWSh7Eamw8XNDV2PdSJN1bdcx3FLbS1Y9jYWaBZ8uDoaCBIb38mCIuQu4Tin7r6QKzAgMBAAECgYB+ICuQB5tEWRyP2ihe2bx421QIcknr5KK2hv452R89GUBfYulrH/iZ9W5SfrbJna6XEuwoxqj4nk3KNEgUgKT9HRBjdKRlqIib2MHiR4uFJjUsg3OTEclo5KPzKAW0QCZBevQ0DNZJUSqYQ/2HUns0Ag7bbfw//F44Uhz9IKgMcQJBAOhwNkJVM1R2soAjdiCq2DdqE+RL1WMHmv98/1FbP/yoFTri+i7CZIyGuuV9064Xh5i82C1qd68ecqRdyA07rtUCQQC06SZiVpNiWxsjE9rSlAhHDMvcm91sILTgJyoNLPouwdLc5D4yiUL/Czc1xf6hcYYAlaqj8tuQpD1T3BXhgn9nAkEAtoMF1+gWugfJ+ZvesZ/0zu5YWDbDg1MBfgOkZzmDcNx6bxay4+x4D2/raS/3+wc2zdPa2y5yc+swkaeh4eIvUQJAagw17PVVJhXD3ZcY8dHG3Gda5XIUpPqzLKaoltqjuV7zDXtaHmOp+zmG3qW2ssqKQ7N4OOz22l38eTkNNok5xwJBALMZRwLWdDQh/qymhs6lPSTGgdQZCwwe4/AeaeS2O0hh8sb9tHXgAMnGAsxjBVEcSTRJVeQ2E9aBlTUquP8sO+k=
-----END PRIVATE KEY-----""",
    },
}


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_pri_key(mch_id):
    return APP_CONF[mch_id]['pri_key']


def _get_pub_key(mch_id):
    return APP_CONF[mch_id]['pub_key']


def dec_to_hex(dec_num):
    return hex(int(dec_num, 10))


def str2hex(string):
    hex_str = ''
    for char in string:
        int_char = ord(char)
        hex_num = hex(int_char).lstrip("0x")
        hex_str += hex_num
    return hex_str


def hex2str(string):
    clear_str = ''
    for counter in xrange(0, len(string), 2):
        hex_char = string[counter] + string[counter + 1]
        clear_str += binascii.unhexlify(hex_char)
    return clear_str


def _gen_sign(message, app_id):
    key = RSA.importKey(_get_pri_key(app_id))
    h = SHA.new(message)
    signer = Signature_pkcs1_v1_5.new(key)
    signature = signer.sign(h)
    return base64.b64encode(signature)


def _gen_pub_sign(message, app_id):
    key = RSA.importKey(_get_pub_key(app_id))
    h = SHA.new(message)
    signer = Signature_pkcs1_v1_5.new(key)
    signature = signer.sign(h)
    return base64.b64encode(signature)


def verify(message, signature, key):
    # _LOGGER.info("onepay verify app_id is: %s", key)
    pub_key = RSA.importKey(key)
    h = SHA.new(message)
    verify_result = Signature_pkcs1_v1_5.new(pub_key).verify(h, signature)
    # _LOGGER.info("onepay verify_result is: %s, 0 mean success", verify_result)
    return verify_result


def generate_sign(parameter):
    s = ''
    for k in sorted(parameter.keys()):
        if k != 'sign' and k != 'signType' and parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    # _LOGGER.info("onepay sign str is: %s", s[:len(s) - 1])
    return s[:len(s) - 1]


def generate_create_res_sign(parameter):
    s = ''
    for k in sorted(parameter.keys()):
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    # _LOGGER.info("onepay create response sign str is: %s", s[:len(s) - 1])
    return s[:len(s) - 1]


def verify_create_response_sign(params, app_id):
    sign = params['sign']
    params.pop('sign')
    params_to_sign = generate_create_res_sign(params)
    if verify(params_to_sign, hex2str(sign), _get_pub_key(app_id)) != 0:
        raise ParamError('onepay sign not pass, data: %s' % params)


def verify_notify_sign(params, app_id):
    sign = params['sign']
    params.pop('sign')
    params_to_sign = generate_sign(params)
    if verify(params_to_sign, sign, _get_pub_key(app_id)) != 0:
        raise ParamError('onepay sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return 'ALIPAY'
    return 'ALIPAY'


def rsa_long_encrypt(pub_key_str, msg, length=117):
    """
    单次加密串的长度最大为 (key_size/8)-11
    1024bit的证书用100， 2048bit的证书用 200
    """
    pubobj = RSA.importKey(pub_key_str)
    pubobj = Cipher_pkcs1_v1_5.new(pubobj)
    res = []
    for i in range(0, len(msg), length):
        res.append(pubobj.encrypt(msg[i:i + length]))
    return "".join(res)


def rsa_long_decrypt(priv_key_str, msg, length=128):
    """
    1024bit的证书用128，2048bit证书用256位
    """
    privobj = RSA.importKey(priv_key_str)
    privobj = Cipher_pkcs1_v1_5.new(privobj)
    res = []
    for i in range(0, len(msg), length):
        res.append(privobj.decrypt(msg[i:i + length], ''))
    return "".join(res)


def convert_bank_name(bank_name):
    if bank_name == BANK_DCT[u'中邮政银行']:
        return 'POSTGC'
    if bank_name == BANK_DCT[u'中信银行']:
        return 'CITIC'
    if bank_name == BANK_DCT[u'交通银行']:
        return 'COMM'
    if bank_name == BANK_DCT[u'广发银行']:
        return 'GDB'
    if bank_name == BANK_DCT[u'平安银行']:
        return 'SPABANK'
    return bank_name


def create_order(order, channel):
    """
    :param order:
    :param channel:
    :return:
    """
    try:
        app_id = channel.appid
        mch = get_account(order.mch_id)

        parameter_dict = {
            "merchantId": app_id,
            "batchNo": '_'.join([str(mch.name), str(order.id)]).zfill(8),
            "batchRecord": 1,
            "currencyCode": "CNY",
            "totalAmount": '%.2f' % float(order.amount),
            "payDate": local_now().strftime('%Y%m%d'),
            "notifyUrl": settings.ONEPAY_WITHDRAW_NOTIFY_URL.format(app_id, order.id),
            "signType": "RSA",

        }

        sign_str = generate_sign(parameter_dict)
        parameter_dict['sign'] = str2hex(_gen_sign(sign_str, app_id))
        parameter_dict['detailList'] = [
            {
                "receiveType": u"个人",
                "accountType": u"储蓄卡",
                "serialNo": '_'.join([str(mch.name), str(order.id)]).zfill(8),
                "amount": '%.2f' % float(order.amount),
                "bankName": convert_bank_name(BANK_DCT[order.pay_account_bank]),
                "subBankName": order.pay_account_bank_subbranch,
                "bankNo": order.pay_account_num,
                "receiveName": order.pay_account_username
            }
        ]

        # 先设置为三方未知状态
        order.status = WITHDRAW_ORDER_STATUS.THIRD_UNKNOWN
        order.third_type = channel.id
        order.save()

        url = _get_gateway(app_id)
        _LOGGER.info("onepay create_withdraw url : %s,  data: %s, order_id: %s" % (url, json.dumps(parameter_dict),
                                                                                   str(order.id)))
        headers = {"Content-Type": "application/json", 'Cache-Control': 'no-cache'}
        response = requests.post(url, data=json.dumps(parameter_dict), headers=headers, timeout=3, verify=False)
        _LOGGER.info("onepay create withdraw res: %s" % response.text)

        # 修改订单状态
        data = json.loads(response.text)
        flag = data.get('flag')
        if flag == "SUCCESS":
            order.status = WITHDRAW_ORDER_STATUS.THIRD
            order.extra_info = response.text
            order.save()
            return True
        else:
            order.detail = data.get('error', '')
            order.status = WITHDRAW_ORDER_STATUS.THIRD_FAIL
            order.extra_info = response.text
            order.save()
            return False
    except Exception, e:
        _LOGGER.info('onpay_withdraw create order fail: %s, %s', e, order.id)
        return False


def check_notify_sign(request, app_id, pay_id):
    order = withdraw_db.get_order(pay_id)
    if not order or order.status not in (WITHDRAW_ORDER_STATUS.THIRD, WITHDRAW_ORDER_STATUS.THIRD_FAIL):
        _LOGGER.info('onepay_withdraw notify order not valid: %s ', pay_id)
        raise ParamError('onepay_withdraw event order not valid: %s' % pay_id)

    rep = json.loads(request.body)

    flag = rep['flag']
    if flag == 'FAILED':
        return
    data = rep['data']

    verify_notify_sign(data, app_id)
    _LOGGER.info("one_withdraw notify data: %s", rep)

    if int(data['status']) != 5:
        order.status = WITHDRAW_ORDER_STATUS.THIRD_FAIL
        order.extra_info = request.body
        order.third_notify_at = datetime.utcnow()
        order.save()
        return

    order.status = WITHDRAW_ORDER_STATUS.DONE
    order.extra_info = request.body
    order.third_notify_at = datetime.utcnow()
    order.save()
    _LOGGER.info("one_withdraw success mch_id: %s, order_id: %s", order.mch_id, order.id)
    notify_success, _ = mch_handler.notify_mch_withdraw(order)
    if not notify_success:
        submit_notify_event(order, TIMER_EVENT_TYPE.MCH_WITHDRAW_NOTIFY)


def query_order(order, channel):
    try:
        app_id = channel.appid
        mch = get_account(order.mch_id)

        parameter_dict = {
            "merchantId": app_id,
            "batchNo": '_'.join([str(mch.name), str(order.id)]).zfill(8),
            "signType": "RSA"
        }
        sign_str = generate_sign(parameter_dict)
        parameter_dict['sign'] = str2hex(_gen_sign(sign_str, app_id))

        url = _get_query_gateway(app_id)
        headers = {"Content-Type": "application/json", 'Cache-Control': 'no-cache'}
        _LOGGER.info(
            "onepay Query withdraw : %s,  data: %s, order_id: %s" % (url, json.dumps(parameter_dict), str(order.id)))

        response = requests.post(url, data=json.dumps(parameter_dict), headers=headers, timeout=3, verify=False)

        _LOGGER.info("onepay Query withdraw response %s" % response.text)

        rep = json.loads(response.text)

        flag = rep['flag']
        if flag == 'FAILED':
            raise ParamError(u'渠道查询报错 %s' % rep.get('errorMsg'))

        data = rep['data']

        if int(data['status']) == 5:
            order.status = WITHDRAW_ORDER_STATUS.DONE

        order.extra_info = response.text
        order.save()
        return order.status
    except Exception, e:
        _LOGGER.info('onepay Query withdraw fail: %s, %s', e, order.id)
        return False
